#encoding=utf-8

import datetime
import time
import urllib
import ujson

from django import forms
from django.contrib import admin
from django.db.models import Count, Max, F, Sum
from django.db.models.query import QuerySet
from django.utils.safestring import mark_safe
from django.utils.html import format_html
from django.contrib.auth.views import login
from django.contrib.auth.models import User,Group
from django.contrib import messages
from andy_manager import settings

from websys.models import (
    UserProfile, HXHUserInfo, HXHPayInfo,PlatformInfo,HXHUserLogin,HXHConsumerInfo,
AgentInfo,UserInfo,GameInfo,RoomInfo,
)
import xadmin
from xadmin.views.list import ResultRow, ResultItem
from websys.admin.AdminLoginForm import AdminAuthenticationForm
from xadmin.views import website
from django.contrib.admin import SimpleListFilter
from xadmin.filters import *#BaseFilter,RelatedFieldListFilter,ListFieldFilter
from django.utils.translation import ugettext_lazy as _
from django.db.models.fields.related import ForeignKey
from django.utils.encoding import smart_unicode
from websys import fun

website.LoginView.login_form = AdminAuthenticationForm
# Register your models here.
#**********************代理页面********************************************
from agentform import (AgentCreationForm, AgentChangeForm,AgentUpdateForm,
                                       AdminPasswordChangeForm, PasswordChangeForm)

from django.forms import ModelForm, PasswordInput
class TwitterUserForm(ModelForm):
    class Meta:
        model =  AgentInfo
        widgets = {
            'password': PasswordInput(),
        }
class TwitterUserAdmin(object):
    form = TwitterUserForm



#代理页面
class AgentInfoAdmin(object):

    def status_state(self, obj):#自定义列
        if obj.status == 0:
            return u'<span style="color:red;font-weight:bold">黑名单</span>'
                   #u'<button type="button" id="my_status_{0}" class="btn btn-success" autocomplete="off"' \
                   #u' onclick="oper_status(\'#my_status_{0}\', \'{0}\', \'{1}\', \'{4}\')">{2}</button>' .format (obj.pk,1,"还原",u"黑名单",obj.account)
        elif obj.status == 1:
            return u'<span style="color:green;font-weight:bold">正常</span>'
                   #u'<button type="button" id="my_status_{0}" class="btn btn-success" autocomplete="off"' \
                   #u' onclick="oper_status(\'#my_status_{0}\', \'{0}\', \'{1}\', \'{4}\')">{2}</button>' .format (obj.pk,0,"拉黑","正常",obj.account)
        else:
            return u'<span style="color:orange;font-weight:bold">%s</span>' % (u"其它",)
    status_state.short_description = u'状态'
    status_state.allow_tags = True

    def ischeck_state(self, obj):#自定义列
        if obj.ischeck == 0:
            return u'<span style="color:red;font-weight:bold">{0}</span>'.format("否")
        elif obj.ischeck == 1:
            return u'<span style="color:green;font-weight:bold">%s</span>' % (u"是",)
        else:
            return u'<span style="color:orange;font-weight:bold">%s</span>' % (u"其它",)
    ischeck_state.short_description = u'审核'
    ischeck_state.allow_tags = True

    def oper_column(self,obj):
        isAdmin=1
        parcid=''#获取登陆的级别cid
        login_uid = self.request.user.username
        parentid = self.request.GET.get("_rel_parentid__id__exact", '')
        if parentid!='':
            par_info=AgentInfo.objects.get(pk=parentid)
            parcid=par_info.classid
        elif  AgentInfo.objects.filter(account=login_uid).exists():#是代理
            a_info=AgentInfo.objects.get(account=login_uid)
            parcid=a_info.classid
            isAdmin=0
        parcid=parcid+","+obj.classid

        t_html=u'<input type="hidden" id="hid_cid_{0}" value=\"{4}\" /><button type="button" id="my_info_{0}" class="btn btn-success" autocomplete="off"' \
                   u' onclick="oper_edit(\'#my_check_{0}\', \'{0}\', \'{1}\', \'{3}\')">{2}</button>&nbsp;&nbsp;' .format (obj.pk,1,"修改",obj.account,parcid)
        if webconfig.RECHARGE_DELELTE:
            t_html += u'<button type="button" id="my_point_{0}" class="btn btn-success" autocomplete="off"' \
                      u' onclick="oper_point(\'#my_point_{0}\', \'{0}\', \'{3}\', \'{2}\', \'{4}\')">{1}</button>&nbsp;&nbsp;'.format(obj.pk, "充值", obj.gamepoint, obj.username, 0)
            t_html += u'<button type="button" id="my_point_{0}" class="btn btn-success" autocomplete="off"' \
                      u' onclick="oper_point(\'#my_point_{0}\', \'{0}\', \'{3}\', \'{2}\', \'{4}\')">{1}</button>&nbsp;&nbsp;'.format(obj.pk, "扣除", obj.gamepoint, obj.username, 1)
        if obj.ischeck == 0 and isAdmin:
            t_html+=u'<button type="button" id="my_check_{0}" class="btn btn-success" autocomplete="off"' \
                   u' onclick="oper_ischeck(\'#my_check_{0}\', \'{0}\', \'{1}\', \'{3}\')">{2}</button>&nbsp;&nbsp;' .format (obj.pk,1,"审核",obj.account)
        if isAdmin:
            t_html += u'<button type="button" id="my_point_{0}" class="btn btn-success" autocomplete="off"' \
                      u' onclick="oper_money(\'#my_point_{0}\', \'{0}\', \'{3}\', \'{2}\', \'{4}\')">{1}</button>&nbsp;&nbsp;'.format(obj.pk, "扣提成", obj.allmoney, obj.username, 1)

        if isAdmin:
            if obj.status == 0:
                t_html+= u'<button type="button" id="my_status_{0}" class="btn btn-success" autocomplete="off"' \
                       u' onclick="oper_status(\'#my_status_{0}\', \'{0}\', \'{1}\', \'{4}\')">{2}</button>' .format (obj.pk,1,"还原",u"黑名单",obj.account)
            elif obj.status == 1:
                t_html+=u'<button type="button" id="my_status_{0}" class="btn btn-success" autocomplete="off"' \
                       u' onclick="oper_status(\'#my_status_{0}\', \'{0}\', \'{1}\', \'{4}\')">{2}</button>' .format (obj.pk,0,"拉黑","正常",obj.account)
        else:
            pass
        return t_html
    oper_column.short_description = u'操作'
    oper_column.allow_tags = True

    def account_next(self,obj):
        return "<a href='/websys/agentinfo?_rel_parentid__id__exact="+str(obj.pk)+"'>"+obj.account+"</a>"
    account_next.short_description = u'帐号'
    #account_next.allow_tags = True

    list_display=('account','gamepoint','username', 'allmoney','status_state','ischeck_state','oper_column')#, 'parentid'
    search_fields=('account', 'parentid__account', 'username')
    list_filter = ('account', 'create_time')#'parentid',
    #fields=('parentid','account', 'discount', 'username', 'create_ip','roomcount',)
    list_exclude = ("id","password","status","classid","discount",'comrate')#页面中不会看到的列

    #添加资源
    def get_media(self):
        media = super(AgentInfoAdmin, self).get_media()
        media.add_css({'screen': ['css/jquery-ui.min.css']})
        media.add_js((self.static('js/jquery.min.js'),))
        media.add_js((self.static('js/jquery-ui.min.js'),))
        media.add_js((self.static('AgentInfoAdminAdmin.js'),))

        return media

    def get_readonly_fields(self):
        if hasattr(self,"org_obj") and (self.org_obj is not None):#修改状态下
            return ('parentid','account')
        return ()
    def get_model_form(self, **kwargs):
        #self.form = AgentCreationForm
        self.fields=('account', 'username','password1','password2')#'parentid',
        if self.org_obj is None:
            # from django.utils.translation import ugettext, ugettext_lazy as _
            # password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
            # password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput,help_text=_("Enter the same password as above, for verification."))

            self.form = AgentCreationForm
        else:
            self.form = AgentUpdateForm

            #self.form.password1.required=False;
            #self.form.password2.required=False;
            #self.get_readonly_fields()#self.readonly_files=('parentid','account')
            #self.fields=('parentid','account', 'username','password', 'discount', 'roomcount',)
        return super(AgentInfoAdmin, self).get_model_form(**kwargs)


    #根据classid找下线(not self.request.user.is_superuser) and
    def queryset(self):
        login_uid = self.user.username
        queryset_all = super(AgentInfoAdmin, self).queryset()

        #print self.request.GET.dict(),'---queryset--agent****'
        parcid=''
        agentids=0
        parentid = self.request.GET.get("_rel_parentid__id__exact", '')
        if parentid!='':
            par_info=AgentInfo.objects.get(pk=parentid)
            parcid=par_info.classid
        elif  AgentInfo.objects.filter(account=login_uid).exists():#是代理
            a_info=AgentInfo.objects.get(account=login_uid)
            agentids=a_info.parentid_id
            parcid=a_info.classid
            #qs = queryset_all.filter(classid__startswith=a_info.classid).exclude(account=login_uid)#like classid%
         #获取当前线下的代理_rel_parentid__id__exact

        # parcid_start=parcid+'100'
        # parcid_end=parcid+'999'
        #AgentInfo.objects.filter(cl)
        if webconfig.RECHARGE_DELELTE and not self.user.is_superuser:
            qs = queryset_all.filter(parentid_id=agentids)
        else:
            qs = queryset_all.filter(classid__regex='^'+parcid+'...$')
        #qs = queryset_all.filter(classid__startswith='100')#.exclude(account=login_uid)

        return qs

    def formfield_for_dbfield(self, db_field, **kwargs):#重写编辑列显示
        if db_field.get_attname() == "parentid_id":#只获取自己下线
            login_uid = self.user.username
            if AgentInfo.objects.filter(account=login_uid).exists():#是代理
                a_info=AgentInfo.objects.get(account=login_uid)
                kwargs["queryset"] = AgentInfo.objects.filter(classid__startswith=a_info.classid)#.exclude(account=login_uid)
        return super(AgentInfoAdmin, self).formfield_for_dbfield(db_field, **kwargs)

    def changelist_view123(self, request, extra_context=None):  #返回表单编辑页面
        #修改时显示列
        t_fields=['parentid','account', 'discount', 'username', 'roomcount',]
        t1=t_fields+[]
        self.fieldsets = ((None, {'fields': tuple(t1.insert(2,'password'))}),
                              # (_('Personal info'), {'fields': ('name', 'email')}),
                              # (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups')}),
                              # (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
                              )
        #新增时显示列
        t_fields.insert(2,'password1');t_fields.insert(3,'password2')
        self.add_fieldsets =((None, {'fields': tuple(t_fields)}),
                             )
        # self.add_fieldsets = ((None, {'classes': ('wide',),
        #                                   'fields': ('username', 'name', 'password1', 'password2', 'email', 'is_active',
        #                                              'is_staff', 'is_superuser', 'groups'),
        #                                   }),
        #                           )

        #print(self.fieldsets ,'---changelist_view--',self.add_fieldsets )
        return super(AgentInfoAdmin, self).changelist_view(request, extra_context)

    def save_models(self):#重写保存操作
        #print '---save_models-00000--'
        obj = self.new_obj
        #是新增还是修改模式，看旧对象是否为空
        is_add = (self.org_obj is None)
        #t_pwd=obj.password
        post_pwd = self.request.POST.get('password1')
        post_pwd_2 = self.request.POST.get('password2')

        par_obj=obj.parentid
        #print '---save_models--11111-'

            #raise forms.ValidationError(self.form.error_messages['password_mismatch'])
        #post_pwd_3=self.form.clean_password2()

        #print '\n'.join(['%s:%s' % item for item in obj.__dict__.items()])
        #print('--save_models--',self.request)
        if is_add:#获取下级的classid
            obj.password=post_pwd
            cid='100'

            if par_obj==None:
                next_arr=AgentInfo.objects.filter(parentid=None).order_by('-classid')
                if len(next_arr)>0:#有下级
                    cid=int(next_arr[0].classid)+1
            else:
                next_arr=AgentInfo.objects.filter(parentid=par_obj).order_by('-classid')
                if len(next_arr)==0:#没下级
                    cid=par_obj.classid+cid
                else:
                    cid=int(next_arr[0].classid)+1

            obj.classid=cid;
            obj.create_ip=fun.GetIP(self.request)
            #print next_arr,'---par_obj---',par_obj,obj,'--save_models--',obj.classid
            #return
            user = User.objects.create_user(obj.account,obj.account,post_pwd)#创建用户
            user.is_staff=1#激活可登陆
            #添加权限
            user.groups.add(Group.objects.get(id=1))
            user.save()
        else:
            if len(post_pwd)!=0:
                #pass#保存密码
                obj.password=post_pwd
                user = User.objects.get(username=obj.account)
                user.set_password(post_pwd)
                user.save()

        #print '---',is_add,self.org_obj,'---save_models---',post_pwd

        obj.save()
    #form = TwitterUserForm

#新页面不是model对应生成的，菜单url配置中的地址对应register_view的
from xadmin.views import BaseAdminPlugin, ModelFormAdminView, ModelAdminView, CommAdminView, csrf_protect_m
from xadmin.util import unquote
from django.utils.html import escape
from xadmin.layout import Fieldset, Main, Side, Row, FormHelper
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.utils.decorators import method_decorator
from django.http import HttpResponseRedirect
from django.views.decorators.debug import sensitive_post_parameters
import websys.webconfig as webconfig
from websys.view import recharge

class MyAgentView(ModelAdminView):
    model = AgentInfo
    change_password_form = AdminPasswordChangeForm
    change_user_password_template = None

    @csrf_protect_m
    def get(self, request, object_id=1):
        if not self.has_change_permission(request):
            raise 123#PermissionDenied
        self.obj = self.get_object(unquote(object_id))
        self.form = self.change_password_form(self.obj)

        #同步收入
        recharge.op_sync_commission(request)

        return self.get_response()

    def get_media_bak(self):
        media = super(MyAgentView, self).get_media()
        media = media + self.vendor('xadmin.form.css', 'xadmin.page.form.js') + self.form.media
        return media

    def get_context(self):
        #代理对象
        login_uid=self.user.username
        ag_info=AgentInfo.objects.get(account=login_uid)
        #下线代理，会员
        # agentnum_all=AgentInfo.objects.filter(classid__startswith=ag_info.classid).count()-1
        # agentnum_next=AgentInfo.objects.filter(classid__regex='^'+ag_info.classid+'...$').count()
        # usernum_next=UserInfo.objects.filter(agentid=ag_info).count()
        usernum_all=UserInfo.objects.filter(agentid__classid__startswith=ag_info.classid).count()

        context = super(MyAgentView, self).get_context()
        #print(context,'-------------------*****get_context*****',)
        helper = FormHelper()
        helper.form_tag = False
        self.form.helper = helper
        context.update({
            #'title': _('Change password: %s') % escape(unicode(self.obj)),
            'form': self.form,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_view_permission': True,
            'original': self.obj,
            #chong add
            'title':_('My Information'),
            'account_view':True,
            'serverval':"服务器上的值",
            'username':ag_info.account,
            #'comrate':ag_info.comrate,
            'allmoney':ag_info.allmoney,
            #'lastmoney':ag_info.lastmoney,
            #'agentnum_all':agentnum_all,
            #'agentnum_next':agentnum_next,
            #'usernum_next':usernum_next,
            'usernum_all':usernum_all,
            #'links':webconfig.SPREAD_LINKS+str(ag_info.pk)
        })
        return context

    def get_response(self):
        #print(self.get_context(),"----******get_response*******",self.admin_site.name)
        return TemplateResponse(self.request, ['myagent.html'] , self.get_context(), current_app=self.admin_site.name)
        #return TemplateResponse(self.request, [ self.change_user_password_template or'xadmin/auth/user/change_password.html']
                               # , self.get_context(), current_app=self.admin_site.name)

    @method_decorator(sensitive_post_parameters())
    @csrf_protect_m
    def post(self, request, object_id):
        if not self.has_change_permission(request):
            raise 23456
        self.obj = self.get_object(unquote(object_id))
        self.form = self.change_password_form(self.obj, request.POST)

        if self.form.is_valid():
            self.form.save()
            self.message_user(_('Password changed successfully.'), 'success')
            return HttpResponseRedirect(self.model_admin_url('change', self.obj.pk))
        else:
            return self.get_response()

#代理的渲染的
xadmin.site.register(AgentInfo, AgentInfoAdmin)
xadmin.site.register_view(r'^agent/info/$', MyAgentView,name='agent_info')
